import axios from 'axios'

import store from '@/store'
import router from '@/router'
const request = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0/'
})

request.interceptors.request.use(function (config) {
  // 除登录页外 其他页发请求都加上token
  if (store.state.user.token && config.url !== 'authorizations') {
    config.headers.Authorization = `Bearer ${store.state.user.token}`
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

request.interceptors.response.use(function (response) {
  // 2XX会进入该代码段
  // 简化返回的数据
  const _data = {
    status: response.status,
    data: response.data.data
  }
  return _data
}, async function (error) {
  // 不是2XX进入改代码段
  // 对响应错误做点什么
  const loginPath = `/login?redirectUrl=${router.currentRoute.path}`
  try {
    if (error.response && error.response.status === 401) {
      const { user } = store.state
      // 没登录
      if (!user.token && !user.refresh_token) {
        throw new Error('did not login')
      }

      // token过期===>重新发请求更新token
      const { data } = await request({
        url: 'authorizations',
        method: 'PUT',
        headers: {
          Authorization: `Bearer ${user.refresh_token}`
        }
      })

      store.commit('setToken', {
        token: data.token,
        refresh_token: user.refresh_token
      })

      return request(error.config)
    }
  } catch (error) {
    router.replace(loginPath)
    return Promise.reject(error)
  }
  return Promise.reject(error)
})

export default request
